<template>
	<div class="transfer_page layer">
		<van-nav-bar :title="`${activeCurr?.name}${$t('transfer')}`" left-arrow
			@click-left="$router.go(-1);$store.commit('clickTransferAddress', {})" :border="false" />
		<div class="cont_page">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" hide-required-asterisk label-width="0"
				class="demo-ruleForm">
				<el-form-item label-width="0" prop="address">
					<van-cell :title="$t('home.transferAddress')" :border="false">
						<el-input v-model="ruleForm.address" :placeholder="$t('home.address')" slot="label"></el-input>
						<img src="@/assets/images/home/wallet/address.png" class="address" slot="right-icon"
							@click="$router.push('/addressBook?id=' + currency_id)" />
					</van-cell>
				</el-form-item>
				<van-cell :title="$t('home.selectNetwork')" :label="activeNetwork.name || $t('pleaseSelectNetwork')" is-link
					:border="false" @click="hasNetwork = !hasNetwork" />
				<p class="tips" style="margin-top: 20px;">{{$t('home.tips')}}</p>
				<el-form-item label-width="0" prop="money">
					<van-cell :title="$t('home.transferNumber')" :border="false">
						<el-input v-model="ruleForm.money" :placeholder="$t('home.number')"
							@input="(val) => ruleForm.money = val.match(/^\d*(\.?\d{0,6})/g)[0]" slot="label">
							<span slot="suffix">{{activeCurr.name}}</span>
						</el-input>
						<div slot="right-icon" style="color:  #0DF5E3;" @click="handleAll">
							{{$t('all')}}
						</div>
					</van-cell>
				</el-form-item>
				<p class="tips">{{$t('home.available')}}:
					{{activeCurr.id == 1 ? userInfo.money : activeCurr.id == 2 ? userInfo.spal:userInfo.spal_legacy }}
					{{activeCurr.name}}
				</p>
				<div class="received">
					<div class="received_title">{{$t('home.receivedQuantity')}}</div>
					<div class="usdt">
						<span>{{accountNum}}</span>
						{{activeCurr.name}}
					</div>
					<div class="commission">
						{{$t('home.commission')}} {{getCommission}} {{activeCurr.name}}
					</div>
				</div>
			</el-form>
			<el-button class="submit_but" :loading="loading" @click="submit">{{$t('home.transferNow')}}</el-button>
		</div>
		<SelectNetwork v-if="hasNetwork" v-model="hasNetwork" :coinId="activeNetwork.network_id" :network="activeCurr.protocol"
			@change="changeNetwork" />
		<PassWork v-if="hasShowPass" v-model="hasShowPass" @success="pay" />
	</div>
</template>

<script>
	import SelectNetwork from './components/selectNetwork.vue'
	import PassWork from '@/components/password.vue'
	import {
		indexWithdrawOrder,
		indexWithdrawFee
	} from '@/api/home'
	export default {
		components: {
			SelectNetwork,
			PassWork
		},
		data() {
			return {
				timeout: null,
				currency_id: '',
				hasNetwork: false,
				loading: false,
				hasShowPass: false,
				activeNetwork: {},
				activeCurr: {},
				getCommission: 0,
				accountNum: 0,
				ruleForm: {
					nework_id: '',
					currency_id: '',
					address: '',
					money: '',
				}
			}
		},
		computed: {
			userInfo() {
				return this.$store.state.userInfo
			},
			currencyList() {
				// console.log('currencyList', this.$store.state.currencyList);
				return this.$store.state.currencyList
			},
			storeAddress() {
				return this.$store.state.address
			},
			rules() {
				let obj = {
					address: [{
						required: true,
						message: this.$t('home.address'),
						trigger: 'change'
					}],
					money: [{
						required: true,
						message: this.$t('home.number'),
						trigger: 'change'
					}]
				}
				return obj
			}
		},
		watch: {
			currencyList: {
				handler(val) {
					if (val && val.length > 0) {
						this.activeCurr = val.find(i => i.id == this.currency_id)
						this.activeNetwork = this.activeCurr.protocol[0]
						// this.ruleForm.currency_id = this.activeCurr.protocol[0].id
						// console.log('watch', this.activeCurr);
					}
				},
				deep: true,
				// immediate: true
			},
			storeAddress: {
				handler(val) {
					// console.log('val',val);
					if (val && val.id) {
						this.ruleForm.address = this.storeAddress.address_all
					}
				},
				deep: true,
				immediate: true
			},
			'ruleForm.money'(val) {
				clearTimeout(this.timeout)
				this.timeout = setTimeout(() => {
					if (this.number != '') {
						this.handleChangeName(val)
					}
				}, 200)
			}
		},
		mounted() {
			this.currency_id = this.$route.query.id
			if (this.currencyList && this.currencyList.length > 0) {
				this.activeCurr = this.currencyList.find(i => i.id == this.currency_id)
				this.activeNetwork = this.activeCurr.protocol[0]
				// this.ruleForm.currency_id = this.activeCurr.protocol[0].id
				// console.log('mounted', this.activeCurr);
			}
		},
		methods: {
			handleAll() {
				// console.log('all');
				this.ruleForm.money = this.activeCurr.id == 1 ? this.userInfo.money : this.activeCurr.id == 2 ? this.userInfo
					.spal : this.userInfo.spal_legacy
			},
			changeNetwork(item) {
				// console.log('changeNetwork', item);
				this.activeNetwork = item
				this.ruleForm.nework_id = item.network_id
			},
			submit() {
				this.$refs.ruleForm.validate(async (valid) => {
					if (valid) {
						if (!this.userInfo.sec_password) {
							this.$toast(this.$t('trade.pleaseSetPaymentPas'))
							this.$router.push('/transactionPassword')
							return
						} else {
							this.hasShowPass = !this.hasShowPass
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			async pay(pas) {
				let money = this.$utils.str16hex(this.$utils.accMul(this.ruleForm.money, 1000000))
				// console.log('^^', { 
				// 	network_id_Xsaf3q: this.activeNetwork.network_id,
				// 	currency_id_XmARCzvq: this.currency_id,
				// 	address_wEeFyPN1: this.ruleForm.address,
				// 	money_VW6BtwJv: money,
				// 	sec_password_bYh48Kln: pas,
				// });
				const res = await indexWithdrawOrder({
					// ...this.ruleForm,
					network_id_Xsaf3q: this.activeNetwork.network_id,
					currency_id_XmARCzvq: this.currency_id,
					address_wEeFyPN1: this.ruleForm.address,
					money_VW6BtwJv: money,
					sec_password_bYh48Kln: pas,
				})
				if (res && res.code == 1) {
					this.$toast.success(res.msg)
					this.hasShowPass = false;
					this.$router.go(-1)
					await this.$store.dispatch('getUserInfo')
				} else {
					this.$toast.fail(res.msg);
					this.hasShowPass = false;
				}
			},
			async handleChangeName() {
				this.loading = true;
				const res = await indexWithdrawFee({
					money: this.ruleForm.money,
					currency_id: this.activeCurr.id,
				}).catch(err => this.loading = false)
				// console.log('res', res);
				if (res && res.code == 1) {
					this.getCommission = res.data.fee
					this.accountNum = (this.ruleForm.money - this.getCommission).toFixed(2)
				}
				this.loading = false;
			}
		}
	}
</script>

<style scoped lang="less">
	.transfer_page {
		min-height: 100vh;
		// overflow-y: scroll;
		// -webkit-overflow-scrolling: touch;

		.cont_page {
			padding: 20px 0;

			.van-cell {
				background-color: #3D3D3D;
				border-radius: 16px;
				padding: 13px 20px;
				align-items: flex-end;
				// margin-bottom: 20px;

				&::after {
					// border-bottom: none;
				}

				::v-deep .van-cell__title {
					text-align: left;
					color: #fff;

					.van-cell__label {
						font-size: 14px;
						color: #fff;
					}
				}

				::v-deep .el-input__inner {
					height: 22px;
					line-height: 22px;
					background-color: transparent;
					padding: 0;
					border: 0;
					color: #fff;

					&::placeholder {
						color: #999;
					}
				}

				::v-deep .el-input__suffix {
					line-height: 22px;
					color: #999;
				}

				.address {
					width: 22px;
					height: 22px;
				}
			}

			.tips {
				text-align: left;
				font-size: 12px;
				margin-bottom: 20px;
			}

			.received {
				padding-top: 40px;

				.received_title {
					margin-bottom: 15px;
				}

				.usdt {
					margin-bottom: 15px;
					display: flex;
					align-items: baseline;
					justify-content: center;

					span {
						font-size: 30px;
						margin-right: 5px;
					}
				}

				.commission {
					margin-bottom: 30px;
				}
			}
		}
	}
</style>